package core;

import util.MyRuntime;
import util.SystemPropertyUtil;

import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicInteger;

public class EventLoopGroup {

    private static final int DEFAULT_EVENT_LOOP_THREADS;

    static {
        DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
                "io.eventLoopThreads", MyRuntime.availableProcessors() * 2));
    }

    private final EventLoop[] children = new EventLoop[DEFAULT_EVENT_LOOP_THREADS];

    private final AtomicInteger idx = new AtomicInteger(0);

    public EventLoopGroup() throws IOException {
        for (int i = 0; i < children.length; i++){
            children[i] = new EventLoop();
        }
    }

    public EventLoop next(){
        // 轮训每一个children
        return children[idx.getAndIncrement() & (children.length - 1)];
    }

    public void register(SocketChannel channel, int ops,int timeout,Handler... handlers){
        next().register(channel,ops,timeout,handlers);
    }
}
